const Base64 = require('../base64');
const key = new Base64();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

function result(status,data,msg){
    this.status = status;
    this.data = data || {};
    this.msg = msg;
}
function Register(req,res){
    MongoClient.connect(url,{useNewUrlParser:true}, function(err,db){
        if(err) throw err;
        var dbo = db.db("mongo");
        dbo.collection('member').find({username:req.body.user}).toArray(async function(memberError,memberRes){
            if( memberError) throw memberError;
            if(memberRes.length==0){                
                var id = await dbo.collection('ids').findOneAndUpdate({"name":"user"},{$inc:{'id':1}},{returnNewDocument :true})
                let reqdata = {
                    username:req.body.user || '',
                    passwd: req.body.passwd || '',
                    member:req.body.member || ''
                };
                for(var i in reqdata){
                    if(!reqdata[i]){
                        res.send(new result(110,'',i+'未填写！'));
                        return
                    }
                };
                // let text =reqdata.username+reqdata.passwd;
                let text = '';
                for(let i = 0;i<reqdata.username.length;i++){
                    text+=(reqdata.username[i]&&reqdata.username[i]+reqdata.passwd[i]&&reqdata.passwd[i])
                }
                let encrypted = key.encode(text).split('').reverse().join('');//加密后的密文密码
                let data = {
                    uid:id.value.id,
                    username:reqdata.username,
                    passwd:encrypted,
                    member:reqdata.member,
                    head:'',
                    CreateTime:Date.parse(new Date())/1000,
                    hash:Math.random().toString(36).substr(2,10)
                }
                dbo.collection('member').insertOne(data, function(err, res) {
                    if (err) throw err;
                    console.log("文档插入成功");
                    db.close();
                });
                res.send(new result(200,{},'注册成功'))      
            }else{
                res.send(new result(101,{},'用户已存在！'))      
            }
        })
    })
  }
  module.exports = Register